<?php


namespace App\Services;


use App\Models\Rule;
use App\Utils\Code;
use App\Utils\Tree;

class RuleService extends BaseService
{

    /**
     * 创建数据
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function store(array $params) {
        if (!$this->checkParams($params)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        $model = new Rule();
        if (isset($params['pid']) && is_numeric($params['pid'])){
            if ($params['pid'] && !$this->show($params['pid'], true, false)){
                throw new \Exception('不存在的上级ID主键', Code::PARAMETER_ERROR);
            }
            $model->pid = (int)$params['pid'];
        }
        if (Rule::where('rule_name', $params['rule_name'])->where('pid', (int)$model->pid)->first()) {
            throw new \Exception('该节点已经存在', Code::EXIST_REPEAT);
        }
        $model->rule_name = $params['rule_name'];
        $model->uri = $params['uri'];
        if (isset($params['sort'])){
            $model->sort = (int)$params['sort'];
        }
        if (isset($params['status'])){
            $model->status = (int)$params['status'];
        }
        $model->save();
        return $this->show($model->rule_id, true);
    }

    /**
     * 数据信息
     * @param $id
     * @param bool $simple
     * @param bool $abnormal
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function show($id, $simple = true, $abnormal = true) {
        $model = Rule::where('rule_id', $id);
        if (!$simple){
            $model = $model->with([]);
        }
        $model = $model->first();
        if (!$model && $abnormal){
            throw new \Exception('不存在的节点ID主键', Code::EMPTY_DATA);
        }
        return $model;
    }

    /**
     * 更新数据
     * @param $id
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function update($id, array $params) {
        if (!$this->checkParams($params, true)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        $model = $this->show($id, true, true);
        if (isset($params['rule_name']) && $params['rule_name']) {
            $model->rule_name = $params['rule_name'];
        }
        if (isset($params['pid']) && is_numeric($params['pid'])){
            $model->pid = (int)$params['pid'];
            $ruleList = Rule::all()->toArray();
            if ($model->pid && in_array($model->pid, Tree::instance()->toChildrenId($model->rule_id, 'rule_id', $ruleList))){
                throw new \Exception('上级主键非法', Code::LACK_OF_CONDITIONS);
            } elseif ($model->pid && !$this->show($model->pid, true, false)) {
                throw new \Exception('不存在的上级ID主键', Code::PARAMETER_ERROR);
            }
        }
        if (isset($params['uri']) && $params['uri']) {
            $model->uri = $params['uri'];
        }
        if (isset($params['sort']) && is_numeric($params['sort'])) {
            $model->sort = $params['sort'];
        }
        if (isset($params['status']) && is_numeric($params['status'])) {
            $model->status = $params['status'];
        }
        $model->save();
        return $model;
    }

    /**
     * 删除数据
     * @param $id
     * @return bool|mixed|null
     * @throws \Exception
     */
    public function destroy($id) {
        if (!$this::$admin) {
            throw new \Exception('你没有删除节点的权限', Code::LACK_OF_CONDITIONS);
        }
        if (Rule::where('pid', (int)$id)->exists()) {
            throw new \Exception('该层级下包含有子级元素', Code::LACK_OF_CONDITIONS);
        }
        return ($this->show($id, true, true))->delete();
    }

    /**
     * 数据列表
     * @param array $params
     * @return array
     */
    public function lists(array $params = []) {
        $lists = Rule::orderBy('sort', 'asc');
        if (isset($params['status']) && is_numeric($params['status'])) {
            $lists = $lists->where('status', (int)$params['status']);
        }
        $lists = $lists->get()->toArray();
        if (isset($params['format']) && $params['format'] == 'list'){
            $lists = Tree::instance()->treeFormat($lists, 'children', null);
        } else {
            $lists = Tree::instance()->toTree($lists, 'rule_id');
        }
        return $lists;
    }

    /**
     * 验证参数
     * @param array $params
     * @param bool $isUpdate
     * @return array
     * @throws \Exception
     */
    private function checkParams(array $params, $isUpdate = false){
        $rules = [
            'rule_name' => ['bail', 'required', 'string', 'between:2,6'],
            'pid' => ['bail', 'integer'],
            'uri' => ['bail', 'required', 'string'],
            'sort' => ['bail', 'integer'],
            'status' => ['bail', 'integer', 'in:0,1']
        ];
        if ($isUpdate){
            // 删除必选条件
            foreach ($rules as $field => &$rule){
                if (isset($rule[1]) && $rule[1] == 'required') {
                    unset($rule[1]);
                }
            }
        }
        $validator = \Validator::make($params, $rules, [], [
            'rule_name' => '节点名称',
            'pid' => '上级主键',
            'uri' => '请求路径',
            'sort' => '排序数值',
            'status' => '可用状态'
        ]);
        if ($validator->fails()) {
            throw new \Exception($validator->errors()->first(), Code::PARAMETER_ERROR);
        }
        return $params;
    }
}
